# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/8/12
library(optparse)
library(magrittr)
library(tidyverse)

paretoNorm <- function(x) {
  (x - mean(x)) / sqrt(sd(x, na.rm = T))
}

option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--cc", default = "calculate_config.json", type = "character", help = "config file"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--o", default = "standard.txt", type = "character", help = "output txt file")
)
opt <- parse_args(OptionParser(option_list = option_list))

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

configJson <- fromJSON(opt$cc)
scaleMethod <- configJson$scaleMethod

data <- read_tsv(opt$i) %>%
  rename(Metabolite = 1)

if (nrow(data) == 0) {
  quit(status = 0)
}

tData <- data %>%
  mutate(Metabolite = factor(Metabolite, levels = unique(Metabolite))) %>%
  gather("SampleID", "Value", -Metabolite, factor_key = T) %>%
  spread(Metabolite, "Value")

outTData <- if (scaleMethod == "scale") {
  tData %>%
    mutate_at(vars(-"SampleID"), function (x){
      scale(x,center = F)
    })
}else if (scaleMethod == "center") {
  tData %>%
    mutate_at(vars(-"SampleID"), function(x) {
      scale(x, scale = F, center = T)
    })
}else if(scaleMethod == "pareto") {
  tData %>%
    mutate_at(vars(-"SampleID"), function(x) {
      paretoNorm(x)
    })
}else{
  tData
}

outTData

outData <- outTData %>%
  gather("Metabolite", "Value", -SampleID, factor_key = T) %>%
  spread(SampleID, "Value")

write_tsv(outData, str_c(opt$o))







